Skip to main content

How do I use the rules section in a pipeline as code?

The rules section in a pipeline as code allows you to define conditions for job execution based on various factors such as changes, variables, or custom expressions. This powerful feature gives you fine-grained control over when a job should run in your pipeline.

Here's how you can use the rules section in your pipeline as code:

Basic rule based on changes:

job1:
script:
- echo "Job 1"

job2:
rules:
- changes:
- path/to/files/*
script:
- echo "Job 2"

In this example, job2 will only execute if there are changes in the specified files or directories. If there are no changes, the job will be skipped.

Rule based on variables:

job1:
variables:
- $VARIABLE == "value"
script:
- echo "Job 1"

job2:
rules:
- exists($VARIABLE)
script:
- echo "Job 2"

In this example, job2 will only run if the variable $VARIABLE exists and is set.

Rule with custom expression:

job1:
variables:
- $ENVIRONMENT == "production"
script:
- echo "Job 1"

job2:
rules:
- $ENVIRONMENT == "production" && $BRANCH == "master"
script:
- echo "Job 2"

In this example, job2 will run if the value of the $ENVIRONMENT variable is "production" and the branch is "master".

Using the rules section, you can define conditional logic for job execution based on changes, variables, or custom expressions. This enables you to create dynamic and flexible pipelines that respond to specific conditions.

Remember to test and validate your pipeline configuration to ensure that the rules are properly defined and meet your desired criteria for job execution.